/**
 * Copyright (C), 2019
 * FileName: CommonFrameFragment
 * Author: Administrator
 * Date: 2019/1/29 11:34
 * Description: 常用框架fragement
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
package com.example.demolearn_2.fragement;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.demolearn_2.R;
import com.example.demolearn_2.activity.DetailActivity;
import com.example.demolearn_2.activity.GuideActivity;
import com.example.demolearn_2.activity.SplashActivity;
import com.example.demolearn_2.base.BaseFragment;
import com.example.demolearn_2.bean.ChinaProvince;
import com.example.demolearn_2.util.OkHttp3Util;
import com.example.demolearn_2.util.PermissionUtils;
import com.example.demolearn_2.util.ToastHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.Inflater;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * @ClassName: CommonFrameFragment
 * @Description: 常用框架fragment
 * @Author: Administrator
 * @Date: 2019/1/29 11:34
 */
public class CommonFrameFragment extends BaseFragment {

    private ListView mListView;
    private List<ChinaProvince> mDataList = new ArrayList<>();
    private CommonFrameFragmentAdapter mAdatpter;
    private ProgressDialog mProgressDialog; // 请求服务器加载数据时的进度对话框

    Handler m_handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 1:
                    mListView.setAdapter(mAdatpter);
                    break;
                default:break;
            }
        } ;
    };

    @Override
    protected View initView() {
        Log.e(CommonFrameFragment.class.getSimpleName(),"第三方框架CommonFrameFragment被初始化了");

        View view = View.inflate(mContext, R.layout.fragment_common_frame, null);
        mListView = (ListView) view.findViewById(R.id.lv_list);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(mContext,"on item click",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(mContext,DetailActivity.class);
                intent.putExtra("item",mDataList.get(position).getId()+";"+mDataList.get(position).getName());
                startActivity(intent);
            }
        });

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    protected void initData(){
//        PermissionUtils.checkPermission(mContext, Manifest.permission.INTERNET,
//                new PermissionUtils.PermissionCheckCallBack() {
//                    @Override
//                    public void onHasPermission() {
//                        // 已授予权限
//                        ToastHelper.show(mContext,"已授予权限");
//                    }
//
//                    @Override
//                    public void onUserHasAlreadyTurnedDown(String... permission) {
//                        // 上一次申请权限被拒绝，可用于向用户说明权限原因，然后调用权限申请方法。
//                        Toast.makeText(mContext, "我们需要"+ Arrays.toString(permission)+"权限", Toast.LENGTH_SHORT).show();
//                    }
//
//                    @Override
//                    public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
//                        // 第一次申请权限或被禁止申请权限，建议直接调用申请权限方法。
////                        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
////                        intent.setData(Uri.parse("package:" + getPackageName()));
////                        startActivityForResult(intent, REQUEST_CODE);
//                        Toast.makeText(mContext, "我们需要"+Arrays.toString(permission)+"权限", Toast.LENGTH_SHORT).show();
//                        // 显示前往设置页的dialog
//                        //showToAppSettingDialog();
//                    }
//                });

                OkHttp3Util.doGet("http://guolin.tech/api/china", null,new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        ToastHelper.show(mContext,"okhttp3:failed");

                        Log.e("OkHttp3Util",e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //ToastHelper.show(mContext,response.body().string());
                        Gson gson = new Gson();
                        mDataList = gson.fromJson(response.body().string(),new TypeToken<List<ChinaProvince>>(){}.getType());
                        mAdatpter = new CommonFrameFragmentAdapter(mContext,mDataList);

                        //更新view
                        Message message = new Message();
                        message.what = 1;
                        m_handler.sendMessage(message);
                    }
                });
    }

    private class CommonFrameFragmentAdapter extends BaseAdapter {

        private final Context mContext;
        private final List<ChinaProvince> mDataList;

        public CommonFrameFragmentAdapter(Context mContext, List<ChinaProvince> mDataList) {
            this.mContext = mContext;
            this.mDataList = mDataList;
        }

        @Override
        public int getCount() {
            return mDataList.size();
        }

        @Override
        public Object getItem(int position) {
            return mDataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
                holder = new ViewHolder();
                holder.textView = (TextView)convertView.findViewById(R.id.tv_content);
                holder.ivPost =  (ImageView) convertView.findViewById(R.id.iv_post);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder)convertView.getTag();
            }

            if(mDataList.size()<=0){
                return convertView;
            }

            holder.textView.setText(mDataList.get(position).getName());
            holder.textView = new TextView(mContext);
            holder.textView.setPadding(10,10,0,10);
            holder.textView.setTextColor(Color.BLACK);
            holder.textView.setTextSize(20);
            ChinaProvince item = mDataList.get(position);
            holder.textView.setText(item.getName());
            return convertView;
        }

        public  class ViewHolder {
            public ImageView ivPost;
            public TextView textView;
        }
    }

    /**
     * 显示进度框
     */
    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setMessage("正在加载...");
            /**
             * dialog.setCancelable(false);dialog弹出后点击屏幕或物理返回键，dialog不消失
             * dialog.setCanceledOnTouchOutside(false);dialog弹出后点击屏幕，dialog不消失；点击物理返回键dialog消失
             */
            mProgressDialog.setCanceledOnTouchOutside(false);
        }
        mProgressDialog.show();
    }

    /**
     * 关闭进度框
     */
    private void closeProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }
}
